const db = wx.cloud.database();
const commodit = db.collection('Shopping');
const shopping = db.collection('Shopping_bak');
Page({
  data: {
    allnumber: 0, //商品总数
    allprice: 0, //总价
    isshow: false, //显示定位地址
    ishidden: true, //是否显示分享好物
    commodit: [], //获取的购物车物品数组
    commodat:[],//推荐物品
    temp: 0,
    youhui: 0, //优惠
    latitude: 0, //经度
    longitude: 0, //纬度
    istrue: false,//全选框的状态
    istrueshan:false,
    isbianji:false //显示编辑还是完成
  },
  onLaunch(options) { //监听小程序初始化。
    
  },
  onShow(options) { //监听小程序启动或切前台
    this.loadListData()
    this.hhuoqudengluxinxi()
  },
  onHide() { //监听小程序切后台。

  },
  onError(msg) { //错误监听函数。
    console.log(msg)
  },
  async hhuoqudengluxinxi(){
    let arr =wx.getStorageSync("userinfo") //获取登录用户的购物车数据
    if(arr==''){
      this.setData({
        commodit:[],
        istrue:false
      })
    }
    else{
      let rte = arr.storeshopping
      let are = []
      for(let i = 0;i<rte.length;i++){
        are[i]=await (await shopping.where({
          _id:rte[i]
        }).get()).data[0]
      }
      console.log(are)
      this.setData({
        commodit:are
      })
      this.jisaun()
    }
  },
  async loadListData() {
    let res = await commodit.get()
    let ras = await shopping.limit(12).get()
    this.setData({
      commodit: res.data,
      commodat:ras.data
    })
    this.panduanshifouquanxuan()
    this.jisaun()
  },
  async jisaun() {
    let avnnumber = 0
    let avnprice = 0
    for (let i in this.data.commodit) {
      if (this.data.commodit[i].isfo) {
        let avn = this.data.commodit[i]
        avnnumber = avn.number + avnnumber
        avnprice = (Math.floor((avn.price * avn.number + avnprice) * 100)) / 100
      }
    }
    let jian = parseInt(avnprice / 300)
    avnprice = (avnprice - 50 * jian).toFixed(2)
    this.setData({
      allnumber: avnnumber,
      allprice: avnprice,
      youhui: 50 * jian
    })
  },

  async xuanze(event) {
    let arr = this.data.commodit
    var i = event.target.dataset.id
    var res =arr[i].isfo
    arr[i].isfo = !arr[i].isfo
    res = !res
    if (res == false) {
      this.setData({
        commodit:arr,
        istrue: false
      })
    }
    commodit.where({
      _id:arr[i]._id
    }).update({
      data: {
        isfo: res
      }
    })
    this.panduanshifouquanxuan()
    this.jisaun()
  },
  async shanjian(event) {
    let arr = this.data.commodit
    var i = event.target.dataset.id
    var res =arr[i].isremove
    arr[i].isremove = !arr[i].isremove
    res = !res
    if (res == false) {
      this.setData({
        commodit:arr
      })
    }
    this.panduanshifouquanxuanshan()
  },
  async panduanshifouquanxuanshan() {
    let htr = this.data.commodit
    let len = 0
    for (let i = 0; i < htr.length; i++) {
      if (htr[i].isremove == true) {
        len++
      }
      else{
        break
      }
    }
    if (len == htr.length&&htr.length>0) {
      this.setData({
        istrueshan: true
      })
    } else {
      this.setData({
        istrueshan: false
      })
    }
  },

  async panduanshifouquanxuan() {
    let htr = this.data.commodit
    let len = 0
    for (let i = 0; i < htr.length; i++) {
      if (htr[i].isfo == true) {
        len++
      }
      else{
        break
      }
    }
    if (len == htr.length&&htr.length>0) {
      this.setData({
        istrue: true
      })
    } else {
      this.setData({
        istrue: false
      })
    }
  },

  async add(event) {
    let arr = this.data.commodit
    var i = event.target.dataset.id
    let res = arr[i].number
    arr[i].number++
    this.setData({
      commodit: arr
    })
    commodit.where({
      _id: arr[i]._id
    }).update({
      data: {
        number: res + 1
      },
      success: res => {
        console.log("更新成功")
      },
      fail: err => {
        console.log("更新失败")
      }
    })
    this.jisaun()
  },
  async reduce(event) {
    let arr = this.data.commodit
    var i = event.target.dataset.id
    let res = arr[i].number
    if (res > 1) {
      arr[i].number = arr[i].number - 1
      this.setData({
        commodit: arr
      })
      commodit.where({
        _id: arr[i]._id
      }).update({
        data: {
          number: res - 1
        }
      })
    } else {
      wx.showModal({
        content: '已经到底了，不能再低了',
        success: function (res) {
          if (res.confirm) { //这里是点击了确定以后
            console.log('用户点击确定')
          } else { //这里是点击了取消以后
            console.log('用户点击取消')
          }
        }
      })
    }
    this.jisaun()
  },
  onReady: function () {
    const _this = this
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        const lat = res.latitude
        const long = res.longitude
        _this.setData({
          latitude: lat,
          longitude: long
        })
      }
    })
  },
  fenxiang: function () {
    let ishenden = !this.data.ishidden
    this.setData({
      ishidden: ishenden
    })
  },
  jiarugouwuche: function (event) {
    //首先传递能表示物品的_id参数
    //在商品集里面查询此_id的物品并获取属性和属性值
    //在购物车中查找是否与此物品匹配的物品
    //有则取消添加购物车，并且修改此物品在购物车中的数量（number）的值（+1）
    //无则向购物车集添加此次物品，数量为1
  },
  async jisuanyemian() {
    let res = await (await commodit.get()).data
    let a = res
    let b = []
    for (let i in a) {
      if (a[i].isfo) {
        b.push(a[i]._id)
      }
    }
    wx.navigateTo({
      url: '/pages/settlement/settlement?_id=' + b + '&price=' + this.data.allprice + '&youhui=' + this.data.youhui,
    })
  },
  async quanxuana() {
    let arr = this.data.commodit
    let res = this.data.istrue
    res = !res
    if (res) {
      for (let i = 0; i < arr.length; i++) {
        arr[i].isfo = true
        commodit.where({
          _id: arr._id
        }).update({
          data: {
            isfo: true
          }
        })
      }
      this.setData({
        commodit: arr
      })

    } else {
      for (let i = 0; i < arr.length; i++) {
        arr[i].isfo = false
        commodit.where({
          _id: arr._id
        }).update({
          data: {
            isfo: false
          }
        })
      }
      this.setData({
        commodit: arr
      })
    }
    this.setData({
      istrue: res
    })
  },
  async quanxuanashan() {
    let arr = this.data.commodit
    let res = this.data.istrueshan
    res = !res
    if (res) {
      for (let i = 0; i < arr.length; i++) {
        arr[i].isremove = true
      }
      this.setData({
        commodit: arr
      })
    } else {
      for (let i = 0; i < arr.length; i++) {
        arr[i].isremove = false
      }
      this.setData({
        commodit: arr
      })
    }
    this.setData({
      istrueshan: res
    })
  },
  async bianji(){
    let isbianji= !this.data.isbianji
    this.setData({
      isbianji:isbianji
    })
  },
  async wancheng(){
    let isbianji= !this.data.isbianji
    let aser = this.data.commodit
    for(let i = 0;i<aser.length;i++){
      if(aser[i].isremove==true){
        aser[i].isremove=false
      }
    }
    this.setData({
      commodit:aser,
      isbianji:isbianji,
      istrueshan:false
    })
  },
  async shanchu(){
    let arr = this.data.commodit
    for(let i in arr){
      if(arr[i].isremove){
        let res = arr[i]._id
       let ret = commodit.where({
          _id:res
        }).remove()
      }
    }
    wx.showModal({
      content: '已经删除了，你将不会再见到它了',
      success: function (res) {
        if (res.confirm) { //这里是点击了确定以后
          console.log('用户点击确定')
        } else { //这里是点击了取消以后
          console.log('用户点击取消')
        }
      }
    })
    this.onShow()
  }
})